<template>
  <q-dialog v-model="open" full-height full-width>
    <q-card>
      <!-- 工具栏 -->
      <q-card-section class="row items-center q-gutter-md" style="height: 72px">
        <q-btn label="确认" color="primary" @click="onSelect" />
        <q-btn outline label="取消" color="primary" @click="onClose" />
        <filter-input :id="id" />
      </q-card-section>

      <!-- 表格 -->
      <q-card-section class="q-pt-none" style="height: calc(100% - 72px)">
        <slot></slot>
      </q-card-section>
    </q-card>
  </q-dialog>
</template>

<script lang="ts">
import { GridApi } from 'ag-grid-community';
import { useFilter } from 'src/components/filter/hooks';
import FilterInput from 'src/components/filter/input.vue';
import { useEmitter } from 'src/emitter';
import { defineComponent, nextTick, PropType, ref, toRefs } from 'vue';

export default defineComponent({
  name: 'grid-dialog',

  components: {
    FilterInput,
  },

  props: {
    id: {
      type: String,
      required: true,
    },
    gridApi: {
      type: Object as PropType<GridApi>,
    },
  },

  emits: ['open', 'close', 'select'],

  setup(props, emits) {
    const open = ref(false);

    const { gridApi } = toRefs(props);
    useFilter(gridApi, { id: props.id });

    useEmitter('dialog', payload => {
      if (payload.close) {
        open.value = false;
      } else if (payload.id === props.id) {
        open.value = true;
        nextTick(() => {
          emits.emit('open');
        });
      }
    });

    const onClose = () => {
      open.value = false;
      emits.emit('close');
    };

    const onSelect = () => {
      open.value = false;
      emits.emit('select');
    };

    return { open, onClose, onSelect };
  },
});
</script>
